import json

from django.shortcuts import render
from django.views import View
from django import forms
from django.forms import Form
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.parsers import JSONParser, FormParser

from my_django import common
from .models import UserInfo, Token
from .serializer import UserInfoSerializer
# Create your views here.


@csrf_exempt
def hello(request):
    return common.json_result({'data': 'hello'})


class ClassApiView(View):

    def get(self, request, *args, **kwargs):
        return common.json_result({'data': 'hello GET'})

    def post(self, request, *args, **kwargs):
        return common.json_result({'data': 'hello POST'})

    def put(self, request, *args, **kwargs):
        return common.json_result({'data': 'hello PUT'})

    def delete(self, request, *args, **kwargs):
        return common.json_result({'data': 'hello DELETE'})


class ClassView(APIView):
    parser_classes = [JSONParser, FormParser]
    def method(self, request, *args, **kwargs):
        self.dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        # 反响URL
        request.versioning_scheme.reverse(viewname='', request=request)
        # parser_classes = [JSONParser, FormParser]
        # 表示解析 content-type:application/json、content-type:x-www-form-urlencoded

        return common.json_result({'data': 'hello GET'})

    def post(self, request, *args, **kwargs):
        user = UserInfoSerializer(data=request.data)
        if not user.is_valid():
            errot = user.errors
            return common.json_result({'error': errot})
        return common.json_result({'data': 'hello POST'})

    def put(self, request, *args, **kwargs):
        return common.json_result({'data': 'hello PUT'})

    def delete(self, request, *args, **kwargs):
        return common.json_result({'data': 'hello DELETE'})


def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(user, encoding='utf-8'))
    m.update(bytes(ctime, encoding='utf-8'))
    return m.hexdigest()


class AuthView(APIView):

    def post(self, request, *args, **kwargs):
        user = request._reuqest.POST.get('username')
        pwd = request._reuqest.POST.get('password')
        user_info = UserInfo.objects.filter(username=user, password=pwd).first()
        token = md5(user_info)
        Token.objects.update_or_create(user=user_info, defaults={'token': token})


class UserGroupView(APIView):

    def post(self, request, *args, **kwargs):

        return common.json_result({'data': 'Ver'})